<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="showRoleFrom">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="roleList" border stripe>
        <!--  展开列 -->
        <el-table-column type="expand">
          <template v-slot="scoped">
            <el-row
              :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']"
              v-for="(item1, i1) in scoped.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag
                  closable
                  @close="removeRightsById(scoped.row, item1.id)"
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级权限和三级权限 -->
              <el-col :span="19">
                <!-- 通过 for 循环 嵌套渲染二级权限 -->
                <el-row
                  :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightsById(scoped.row, item2.id)"
                      >{{ item1.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      type="warning"
                      closable
                      @close="removeRightsById(scoped.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <el-button size="mini" type="primary" icon="el-icon-search" @click="editRoles(scope.row)">编辑</el-button
            >
            <el-button size="mini" type="danger" icon="el-icon-delete"
             @click="removeRoleById(scope.row)" >删除</el-button
            >
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限的对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="40%"
    >
      <!-- 树形列表 -->
      <el-tree
        show-checkbox
        :data="rightList"
        :props="treeProps"
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addRoleDialogVisible"
      width="40%"
      @close="addRoleDialogClosed('addAndUpdateRoleFormRef')"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="addAndUpdateRoleForm"
        ref="addAndUpdateRoleFormRef"
        :rules="addAndUpdateRoleFormRules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addAndUpdateRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addAndUpdateRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="EditDialogVisible"
      width="40%"
      @close="addRoleDialogClosed('addAndUpdateRoleFormRef')"
      >
      <el-form 
        :model="addAndUpdateRoleForm"
        label-width="80px"
        ref="addAndUpdateRoleFormRef"
        :rules="addAndUpdateRoleFormRules">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addAndUpdateRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addAndUpdateRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="EditDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="EditRoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 角色列表数据
      roleList: [],
      // 是否显示权限对话框
      setRightDialogVisible: false,
      // 所有权限的数据
      rightList: [],
      // 树形控件的属性绑定对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认节点Id数组
      defKeys: [104],
      // 当前即将分配权限的角色id
      roleId: '',
      /* 添加角色对话框 */
      addRoleDialogVisible: false,
      // 修改角色对话框
      EditDialogVisible: false,
      /* 添加角色表单 */
      addAndUpdateRoleForm: {
        roleId: '',
        roleDesc: '',
        roleName: ''
      },
      /* 添加角色校验表单 */
      addAndUpdateRoleFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          {
            min: 2,
            max: 10,
            message: '用户账号长度在 2 到 10 个字符',
            trigger: 'blur'
          }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '用户账号长度在 3 到 10 个字符',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    /* 获取所有角色列表 */
    async getRoleList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        this.$message.error('获取角色列表失败')
      }
      this.roleList = res.data
      console.log('roles', res.data)
    },
    /* 删除权限 */
    removeRightsById(roles, rightId) {
      this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `roles/${roles.id}/rights/${rightId}`
          )
          if (res.meta.status !== 200) {
            return this.$message.error('删除权限失败!')
          }
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          roles.children = res.data
          return false
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    /* 显示权限对话框 */
    async showSetRightDialog(role) {
      this.roleId = role.id
      // 清空之前默认节点Id数组
      this.defKeys = []
      // 获取所有权限数据
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        this.$message.error('请求权限列表失败！')
      }
      this.rightList = res.data
      // 递归获取三级节点的Id
      this.getLeafkeys(role, this.defKeys)
      // 打开权限对话框
      this.setRightDialogVisible = true
    },
    /* 通过递归形式，获取角色下所有三级权限的id，并保存到 defKeys 中 */
    getLeafkeys(node, arr) {
      // 当前节点不包含 children 说明是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      // 递归
      node.children.forEach(item => {
        this.getLeafkeys(item, arr)
      })
    },
    /* 点击为角色分配权限 */
    async allotRights() {
      /* 获取当前树中 选中的节点id 和 半选中节点id 数组 */
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(), // 选中节点id
        ...this.$refs.treeRef.getHalfCheckedKeys() // 半选中节点id
      ]
      // 添加字符串
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败！')
      }
      this.$message.success('分配权限成功')
      // 获取所有角色列表
      this.getRoleList()
      // 隐藏对话框
      this.setRightDialogVisible = false
    },
    showRoleFrom() {
      // 将添加角色表单清空
      this.addAndUpdateRoleForm = {}
        // 显示添加角色对话框
      this.addRoleDialogVisible = true
    },
    /* 添加角色 */
    addRole() {
      this.$refs.addAndUpdateRoleFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('roles', this.addAndUpdateRoleForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加角色失败！')
        }
        this.$message.success('添加角色成功')
        // 重新查询角色列表
        this.getRoleList()
        // 关闭角色列表
        this.addRoleDialogVisible = false
      })
    },
    /* 添加角色关闭回调 */
    addRoleDialogClosed(RoleFormName) {
      this.$refs[RoleFormName].resetFields()
    },
    /* 编辑当前用户 */
    async editRoles (roles) {
      const { data: res } = await this.$http.get(`roles/${roles.id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户信息失败！')
      }
      this.addAndUpdateRoleForm = res.data
      console.log('RoleForm',this.addAndUpdateRoleForm)
      this.EditDialogVisible = true
    },
    /* 保存修好的角色 */
    EditRoles () {
      this.$refs.addAndUpdateRoleFormRef.validate(async valid => {
        if (!valid) return
        const { roleName, roleDesc, roleId } = this.addAndUpdateRoleForm
        const { data: res } = await this.$http.put(`roles/${roleId}`, { roleName, roleDesc })
        if(res.meta.status !== 200) {
          return this.$message.error('编辑用户失败！')
        }
        this.$message.success('编辑用户成功！')
        // 关闭修改对话框
        this.EditDialogVisible = false
        // 重新查询角色列表
        this.getRoleList()
      })
    },
    /* 删除当前角色 */
    removeRoleById (Roles) {
      this.$confirm(`此操作将永久删除该角色【${Roles.roleName}】, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete('roles/' + Roles.id)
        if (res.meta.status !== 200) {
          this.$message({
            type: 'error',
            message: '删除失败!'
          })
          return
        }
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        // 重新角色获取数据
        this.getRoleList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 6px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
